package com.wangzz.mallchat.common.common.config;

import com.wangzz.mallchat.common.common.thread.MyThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 统一线程池配置
 */
@Configuration
@EnableAsync  // 开启使用async
public class ThreadPoolConfig implements AsyncConfigurer {

    public static final String MALLCHAT_EXECUTOR = "mallChatExecutor";

    public static final String SOCKET_EXECUTOR = "socketExecutor";

    // 给async指定线程池
    @Override
    public Executor getAsyncExecutor() {
        return mallChatExecutor();
    }

    @Bean(MALLCHAT_EXECUTOR)  // 返回spring提供的线程池
    @Primary // 当bean类型重复时，优先使用
    public ThreadPoolTaskExecutor mallChatExecutor() {
        // 配置的线程池交给spring进行管理，
        // 这样spring会帮我们创建线程池，并管理线程池的生命周期，当停机时spring会回调destroy方法关闭线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  //spring 提供的线程池
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(200);
        executor.setThreadNamePrefix("mallChat-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 线程拒绝策略，让调用者自己执行
        // 配置优雅停机，阻塞等待任务执行完
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadFactory(new MyThreadFactory(executor));
        executor.initialize();
        return executor;
    }
}
